package com.qidian.test;

import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.concurrent.atomic.AtomicInteger;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;


public class SendFileByHttp extends Thread 
{
//	static String serverURL = "http://116.255.202.169:8888" ;
//	static String maskCode = "1S57e8592a8552431488443f340e14e561" ;
	
	static String serverURL = "http://127.0.0.1/MServer" ;	
	static String maskCode= "2S9e87ac91db0e42a1bde2f821ac70605d";
	
	//1S57e8592a8552431488443f340e14e561

//	static String serverURL = "http://116.255.206.83:8888" ;
//	static String maskCode = "2@7b313bff44824be688631177e57ff2ec" ;

//	static String serverURL = "http://218.106.254.126" ;	
//	static String maskCode= "2@30d343c38023431f9846e3ae7e5eef60";

	static AtomicInteger count = new AtomicInteger(0) ;
	static AtomicInteger wrong = new AtomicInteger(0) ;
	static int num_threads = 1 ;
	static int num_sendTimes = 100 ;
	static int timeOut = 5 ;
	
   	String gameType = "1001" ;
    String interval = "30" ;
    String path = "C:\\4.jpg";
//    String rUser = "root_mserver" ;
    String rUser = null ;
    long uPoint = 0 ;


    public static String getMimeType(String fileUrl)throws java.io.IOException  
    {  
        FileNameMap fileNameMap = URLConnection.getFileNameMap();  
        String type = fileNameMap.getContentTypeFor(fileUrl);  
        return type;  
    }
	
	public void run()
	{

       String[] results = new String[num_sendTimes] ;
       String dir = "D:/ttt/" ;
       for (int i = 0 ; i < num_sendTimes ; i ++)
       {    	   
    	   File file = new File(dir+i+".jpg");
    	   if (file.length() < 4*1024)
    		   gameType = "1002";
    	   else
    		   gameType = "1001" ;
    	   results[i] = sendFile(maskCode,gameType,interval,file.getPath(),uPoint,rUser) ;
//    	   results[i] = sendFile(maskCode,gameType,interval,path,uPoint,rUser) ;
    	   System.out.println(results[i]) ;
//    	   System.out.println(Thread.currentThread().getId()+":"+count.incrementAndGet()+":"+results[i]) ;
       }
       
       for (int i = 0 ; i < num_sendTimes ; i ++)
       {   
    	   
       	   for (int j = 0 ; j < 30 ; j ++)
    	   {
       		   String answer = getAnswer(maskCode,results[i]) ;
       		   System.out.println(answer) ;
       		   try {
       			Thread.sleep(2000) ;
           	   } catch (InterruptedException e) {
       			e.printStackTrace();
           	   }   
           	   if (!answer.endsWith("-2"))
           		   break ;
    	   }
       }
       
       
       for (int i = 0 ; i < num_sendTimes ; i ++)
       {   
    	   report(maskCode,results[i]) ;
       }
       
       
	}

	public static String getAnswer( String pMaskCode,String pID)
	{
	    String result = "OK" ;
	    String url = serverURL+"/answer" ;
	    url += "?actionType=getAnswer&msgId="+pID+"&account="+pMaskCode+"&_="+System.currentTimeMillis();
        GetMethod httpGet = new GetMethod(url) ;
        
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(20000);// 设置连接时间
        try
        {
            int status = client.executeMethod(httpGet);
            if (status != HttpStatus.SC_OK) 
            {
                result = "服务器访问失败" ;
            }
            else if (status == HttpStatus.SC_OK) 
            {   
                result = httpGet.getResponseBodyAsString() ;
            }     
        }
        catch (IOException e)
        {
            e.printStackTrace();
            result = "网络异常" ;
        }
        httpGet.releaseConnection() ;
	    return result ;
	}
	
	public static String report(String pMaskCode,String pID)
	{
        String result = "OK" ;
        String url = serverURL+"/answer" ;

        url += "?actionType=report&msgId="+pID+"&account="+pMaskCode;
        GetMethod httpGet = new GetMethod(url) ;
        
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(20000);// 设置连接时间
        try
        {
            int status = client.executeMethod(httpGet);
            if (status != HttpStatus.SC_OK) 
            {
                result = "服务器访问失败"+status ;
            }
            else if (status == HttpStatus.SC_OK) 
            {   
                result = httpGet.getResponseBodyAsString() ;
            }     
        }
        catch (IOException e)
        {
            e.printStackTrace();
            result = "网络异常" ;
        }
        httpGet.releaseConnection() ;
        
        return result ;
	}
	
	public static String sendFile( String pMaskCode, 
	        String pGameType,
	        String pInterval,
	        String path,
	        long uPoint,
	        String rUser)
	{
		long start = System.currentTimeMillis() ;
	   String result = "0" ; 
       String url = serverURL +"/file" ;

       PostMethod httpPost = null ;
       HttpClient client = null ;
       try
       {    
           url += "?actionType=sendFile&account="+pMaskCode+"&gameType="+pGameType + "&interval="+pInterval ;
           url += "&returnUser="+rUser+"&point="+uPoint ;
           FilePart fp = new FilePart("filePath", new File(path)); 
           fp.setContentType(getMimeType(path));
           Part[] parts = {fp}; 
           
           httpPost = new PostMethod(url);
           httpPost.setRequestHeader("Connection", "close");
           MultipartRequestEntity mre=new MultipartRequestEntity(parts,httpPost.getParams());
           httpPost.setRequestEntity(mre);
           
           client = new HttpClient();
           client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut*1000);// 设置连接时间
           client.getHttpConnectionManager().getParams().setSoTimeout(timeOut*1000) ;
           int status = client.executeMethod(httpPost);
           if (status != HttpStatus.SC_OK) 
               result = "服务器访问失败" ;
           else if (status == HttpStatus.SC_OK) 
               result = httpPost.getResponseBodyAsString() ;
           
       }
       catch (Exception e) 
       {
    	   System.out.println(e.getMessage()) ;
    	   wrong.incrementAndGet() ;
           result = "网络异常" ;
       }
       finally{
    	   if (httpPost != null)
    		   httpPost.releaseConnection();
       }
       long timeCost = (System.currentTimeMillis()-start)/1000 ;
       if (timeCost >= 3)
    	   System.out.println("Time cost:"+timeCost+" seconds") ;
       return result;	    
	}
	

	public static void main(String [] args) throws InterruptedException 
	{

		if (args.length >= 2)
		{
			num_threads = Integer.parseInt(args[0]) ;
			num_sendTimes = Integer.parseInt(args[1]) ;
		}
		if (args.length >= 3 )
			timeOut = Integer.parseInt(args[2]);
		if (args.length >= 4)
			maskCode = args[3] ;
       Thread[] pluginThread = new SendFileByHttp[num_threads] ;
       for(int i = 0 ;i < num_threads ; i ++)
       {
    	   pluginThread[i] = new SendFileByHttp() ;
       }
       for(int i = 0 ;i < num_threads ; i ++)
       {
    	   Thread.sleep(100) ;
    	   pluginThread[i].start() ;
       }
       
       
	      
       return ;
   }

}
